package org.metasketch.simulator.runtime;

import org.metasketch.logger.Log;
import org.metasketch.simulator.configuration.SimulationPackage;
import org.metasketch.simulator.configuration.loaders.DynamicResourceConfig;
import org.metasketch.simulator.configuration.loaders.SimulationConfig;
import org.metasketch.simulator.configuration.loaders.StaticResourceConfig;
import org.metasketch.simulator.transformation.PetriNetSimulationPackage;

public class SimulatorEngine {

	Long currentTime;

	ProcessManager processManager = new ProcessManager();
	ArrivalsManager arrivalsManager = new ArrivalsManager();
	ResourceResolver resourceResolver = new ResourceResolver();

	PetriNetSimulationPackage simulPackage;

	SimulationConfig simulationConfig;
	StaticResourceConfig staticResourceConfig;
	DynamicResourceConfig dynamicResourceConfig;

	private SimulationPackage simulPackage2;

	public void initialize(PetriNetSimulationPackage simulPackage,
			SimulationPackage simulPackage2) {
		this.simulPackage = simulPackage;
		this.simulPackage2 = simulPackage2;
		
		simulationConfig = simulPackage2.getSimulationConfig();
		staticResourceConfig = simulPackage2.getStaticResourceConfig();
		dynamicResourceConfig = simulPackage2.getDynamicResourceConfig();
	}

	public void startSimulation() throws Exception {

		Log.println("Initializing Simulation...");

		currentTime = 0l;

		arrivalsManager.setSimulPackage(simulPackage);
		arrivalsManager.setDynamicResourceConfig(dynamicResourceConfig);
		arrivalsManager.setManager(processManager);
		arrivalsManager.initialize();


		// resourceManager.setStaticResourceConfig(staticResourceConfig);
//		resourceManager.initialize();

		resourceResolver.setSimulPackage(simulPackage);
		resourceResolver.setSimulPackage2(simulPackage2);
		resourceResolver.initialize();

		processManager.setResourceResolver(resourceResolver);

		Log.println("Starting Simulation...");

		int printCounter = 0;

		while (currentTime <= simulationConfig.getTime()) {
			arrivalsManager.createNewArrivals(currentTime);
			processManager.manageCurrentProcesses(currentTime);

			if (printCounter == 3600) {
				Log.println("time: " + currentTime);
				printCounter = 0;
			}
			printCounter++;

			currentTime++;
		}

		Log.println("Finished Simulation.");

	}

}
